const express = require('express');
const router = express.Router();
const { Category , Course } = require('../../models');  
const { Op } = require('sequelize');  //模糊匹配查询
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');
//列表查询 
router.get('/', async function(req, res, next) {
    try{
   
    //当前是第几页  
    const currentPage = Math.abs(Number(req.query.currentPage)) || 1;
    //每页显示多少条
    const pageSize = Math.abs(Number(req.query.pageSize))|| 10;
    //计算 offset
    const offset = (currentPage - 1) * pageSize; 

    const condition ={  //倒序
        order: [['rank', 'ASC'], ['id', 'ASC']],
        limit: pageSize,
        offset
    } 
    if(req.query.name){  //模糊匹配
        condition.where = { 
            name: {
                [Op.like]: `%${req.query.name}%`
            }
        }
    }  
    // const categories =await Category.findAll(condition)
    const {count ,rows} =await Category.findAndCountAll(condition)
    success(res,'success', {
        categories: rows,
        pagination: {
            total: count,
            currentPage,
            pageSize
        } 
    },200)
    }catch(err){
        failure(res,err)
    }
});
//新增
router.post('/', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        const category = await Category.create(body)
        success(res,'success', category,201)
        }catch(err){
            failure(res,err)
        }
});
//id占位查询
router.get('/:id', async function(req, res, next) {
    try{
        const category = await getCategory(req)
        success(res,'success', category,201)
    }catch(err){
        failure(res,err)
    }
});
//删除分类
router.delete('/:id', async function(req, res, next) {
    try{
    const category = await getCategory(req)
    //判断 有没有课程表（Course）关联的 分类id
    const count = await Course.count({ where: { categoryId: req.params.id } });
    if (count > 0) {
      throw new Error('当前分类有课程，无法删除。');
    }
    await category.destroy()
        success(res,'success', {
            status: true,
            msg: '删除成功',
        },201)
    }catch(err){
        failure(res,err)
    }
})
//修改分类
router.put('/:id', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        const category = await getCategory(req)
        await category.update(body)
        success(res,'success', {
            status: true,
            msg: '更新成功',
            data:{category}
        },200)
    }catch(err){
        failure(res,err)
    }
})
const bodyFilter = ['name','rank']
function filterBody(body) {
    const result = {}
    bodyFilter.forEach(key => {
        if(body[key]){
            result[key] = body[key]
        }
    })
    return result
}
async function getCategory(req) {
     const condition = {
        include: [
          {
            model: Course,
            as: 'courses',
          },
        ],
      //   order:[['id','desc']],
      //   limit: pageSize,
      //   offset
      }
    const { id } = req.params;
    const category = await Category.findByPk(id,condition)
    if( !category ) throw new NotFoundError(`ID:${id} 的分类不存在`)
    return category
}
module.exports = router;
